from RedisTool import r
from flask import Blueprint, request, jsonify
from application.models.users.user import db,  Course, Tcourse

course_blue = Blueprint("course_blue", __name__)


# 获取课程详情
@course_blue.route("/getDetail",methods=["GET"])
def getDetail():
    # 获取id
    cid = request.args.get("cid")
    userid = request.args.get("userid")
    # 查询课程信息
    course = Course.query.filter(Course.id == cid).first()
    # 加入浏览记录，获取到userid
    if userid:
        key = "collection" + str(userid) + 'pro' + str(cid)
        r.hash_add(key, "id", course.id)
        r.hash_add(key, "name", course.name)
        r.hash_add(key, "url", course.url)
    # 返回课程信息
    course = {"id": course.id, "name": course.name, "url":course.url}
    return jsonify({"code": 200, "course": course})


# 获取最近浏览
@course_blue.route("/getViews",methods=["GET"])
def getViews():
    # 获取id
    userid = request.args.get("userid")
    findkey = "collection" + str(userid) + '*'
    gidlist = r.getvalues(findkey)
    reslist = []
    for i in gidlist:
        goods = r.getall_hash(i)
        dict = {}
        for k, v in goods.items():
            kk = k.decode()
            vv = v.decode()
            dict[kk] = vv
        reslist.append(dict)
    return jsonify({"code":200,"list":reslist})


# 加入购物车
@course_blue.route("/buy",methods=["GET"])
def buy():
    # 获取参数 userid courseid
    userid = request.args.get("userid")
    courseid = request.args.get("courseid")
    # 加减类型
    type = 1
    try:
        type = request.args.get("type")
    except:
        pass
    # 从hash中获取数据，如果存在数量+1 buy1course2
    key = "buy"+str(userid)+"course"+str(courseid)
    # 如果不存在存入redis hash
    flag = r.findkey_hash(key)
    # 存在
    if flag:
        # 数量+1
        ff = r.jiajian_hash(key,"number",1,type)
        if ff == False:
            return jsonify({"code":200,"msg":"不能在减了"})
    else:
        r.jiajian_hash(key,"id",courseid)
        r.jiajian_hash(key,"number",1)
    return jsonify({"code":200,"msg":"加入购物车成功"})


# 获取购物车
@course_blue.route("/mycart", methods=["GET"])
def mycart():
    # 获取参数userid
    userid = request.args.get("userid")
    # 从hash中获取商品id和数量
    key = "buy"+str(userid)+"*"
    goods = r.getvalues(key)
    glist =[]
    tmoney = 0
    tcount = 0
    if goods:
        for i in goods:
            # 获取每一条商品的具体信息
            good = r.getall_hash(i)
            rescourse={}
            for k,v in good.items():
                params = k.decode()
                values = v.decode()
                if params == "id":
                    tcourse = Tcourse.query.filter(Tcourse.id == values).first()
                    rescourse["id"] = tcourse.id
                    rescourse["name"] = tcourse.title
                    rescourse["url"] = tcourse.url
                    rescourse["price"] = tcourse.price
                if params == "number":
                    # 获取到数据库商品数量
                    rescourse["number"] = values
                    print("values",values)
            rescourse["total"] = int(rescourse["price"]) * int(rescourse["number"])
            # 计算总价格
            tmoney = float(tmoney) + float(rescourse["total"])
            tcount = int(tcount) + int(rescourse["number"])
            glist.append(rescourse)
    # 价格，图片，名字      从mysql中获取，从redis商品缓存中读取
    # 数据重组返回
    return jsonify({"code":200,"glist":glist,"tmoney":tmoney,"tcount":tcount})


# 获取训练营课程
@course_blue.route("/bootcamp", methods=["GET"])
def bootcamp():
    # 获取数据库存储的所有训练营课程
    trouse = Tcourse.query.all()
    # 序列化
    clist = [{"id":i.id,
              "name":i.title,
              "url":i.url,
              "price":i.price,
              "store":i.store,
              "intor":i.intro
              }for i in trouse]
    # 返回
    return jsonify({"code":200,"clist":clist})











